<script setup>
import BackTop from '@/components/BackTop.vue'
import { onBeforeUnmount, onMounted } from 'vue'
import { useOptionStore, useStuStore } from '@/stores/'
import { socket } from '@/utils/socket'
import { useRouter } from 'vue-router'
import { h } from 'vue'
import { ElNotification } from 'element-plus'
import { useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const stuStore = useStuStore()
const optionStore = useOptionStore()
const dark = () => {
  if (optionStore.themeSwitch) {
    document.documentElement.classList.add('dark')
  }
}

const handleUnLoad = () => {
  socket.emit('deleteClientSocket', stuStore.stuInfo.id)
}

onMounted(() => {
  socket.on('connect', () => {
    console.log('socket连接成功')
    socket.on('stuMessage', (data) => {
      if (route.path !== '/') {
        ElNotification({
          title: '新通知，请点击下方跳转查看',
          type: 'warning',
          message: h(
            'span',
            {
              style: 'color:#409eff;cursor: pointer;',
              onClick: () => {
                router.push('/')
              }
            },
            '点击跳转'
          )
        })
      } else {
        ElNotification({
          title: '新通知!',
          message: h(
            'span',
            {
              style: 'color:#409eff;'
            },
            data.content
          ),
          type: 'warning'
        })
      }
      stuStore.getMesList()
    })

    socket.on('paperStatus', (data) => {
      if (route.path === '/paper') {
        ElNotification({
          title: '考试通知!',
          message: h(
            'span',
            {
              style: 'color:#409eff;cursor: pointer;'
            },
            `${data}，请刷新页面`
          ),
          type: 'warning'
        })
      } else {
        ElNotification({
          title: '考试通知!',
          message: h(
            'span',
            {
              style: 'color:#409eff;cursor: pointer;'
            },
            data
          ),
          type: 'warning'
        })
      }
    })
  })
  dark()
  const uid = localStorage.getItem('uid')
  if (uid) {
    socket.emit('stuMessageClient', uid)
    socket.emit('paperStatusClient', uid)
  }
  window.addEventListener('beforeunload', handleUnLoad)
})

onBeforeUnmount(() => {
  window.removeEventListener('beforeunload', handleUnLoad)
})
</script>

<template>
  <RouterView />
  <BackTop></BackTop>
</template>

<style scoped></style>
